//
//  myQuestViewController.m
//  YuTang
//
//  Created by 葛悦彣 on 2024/8/6.
//

#import "myQuestViewController.h"
#import "myQuestListModel.h"
#import "myQuestTableViewCell.h"
#import "myQuestHeaderView.h"
#import "DTChoosePersonListShowView.h"
#import "YTSelectStringShowView.h"
#import "PersonInCchargeShowView.h"
#import "ClockViewController.h"
#import "TransferTaskViewController.h"
#import "CancelTaskViewController.h"

@interface myQuestViewController ()<UITableViewDelegate,UITableViewDataSource>
///全部
@property (nonatomic ,strong) UIButton * qbBtn;
///待办
@property (nonatomic ,strong) UIButton * dbBtn;
@property (nonatomic ,strong) UILabel * dblab;
///未完成
@property (nonatomic ,strong) UIButton * ywcBtn;
@property (nonatomic ,strong) UIView * btnline;

///时间
@property (nonatomic ,strong) NSString * executeStartTime;
@property (nonatomic ,strong) NSString * executeEndTime;
@property (nonatomic ,strong) NSString * executeTime;
@property (nonatomic ,strong) NSString * xsuser;

@property (nonatomic ,strong) NSMutableArray <myQuestListModel *> * modelArray;

@property (nonatomic ,strong) myQuestHeaderView * headerview;
@property (nonatomic ,strong) myQuestTimeListModel * model;

@property (nonatomic ,strong) NSURLSessionDataTask * task;
@property (nonatomic ,strong) NSURLSessionDataTask * modeltask;

@end

@implementation myQuestViewController

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self loadTimeApi];
}

-(NSMutableArray<myQuestListModel *> *)modelArray{
    if(!_modelArray){
        _modelArray = [NSMutableArray array];
    }
    return _modelArray;
}

-(NSString *)executeStartTime{
    if(!_executeStartTime){
        NSDate * date = [NSDate new];
        NSCalendar * calendar = [NSCalendar currentCalendar];
        NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init];
        dateFormatter.dateFormat = @"yyyy-MM-dd";
        NSDateComponents *components = [calendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitWeekday fromDate:date];
        //周几
        NSInteger weekDay = components.weekday;
        //几号
        NSInteger day = components.day;
        
        NSInteger startDiff, endDiff;
        if (weekDay == 1) {
            startDiff = -6;
            endDiff = 0;
        } else {
            startDiff = calendar.firstWeekday - weekDay - 1;
            endDiff = 7 - weekDay;
        }
        
        components.day = day + startDiff;
        NSDate *startDate = [calendar dateFromComponents:components];
        
        //        components.day = day + endDiff;
        //        NSDate *endDate = [calendar dateFromComponents:components];
        
        _executeStartTime = [dateFormatter stringFromDate:startDate];
        self.executeEndTime = [dateFormatter stringFromDate:date];
        self.executeTime = [dateFormatter stringFromDate:date];
    }
    return _executeStartTime;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.shutDownBack = YES;
    
    UIView * topview = [UIView new];
    [self.view addSubview:topview];
    topview.backgroundColor = KcolorHex(@"#F1F5FA");
    [topview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.offset(0);
        make.height.offset(kwt(50));
    }];
    
    UIButton * qbbtn = [UIButton buttonWithType:0];
    self.qbBtn = qbbtn;
    qbbtn.addTarget(self,@selector(qbBtnClick));
    qbbtn.addNormalText(@"全部").addNormalColor(KcolorHex(@"#222222")).addFont(kFont(17));
    [topview addSubview:qbbtn];
    [qbbtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.top.offset(0);
        make.width.offset(kwt(80));
    }];
    
    UIButton * dbBtn = [UIButton buttonWithType:0];
    self.dbBtn = dbBtn;
    dbBtn.addTarget(self,@selector(dbBtnClick));
    dbBtn.addNormalText(@"待办").addNormalColor(KcolorHex(@"#222222")).addFont(kFont(17));
    [topview addSubview:dbBtn];
    [dbBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.top.offset(0);
        make.left.equalTo(qbbtn.mas_right);
        make.width.offset(kwt(80));
    }];
    
    UILabel * dblab = [DTKTool labelWithText:@"0" andFont:kCFont(10) andTextColor:UIColor.whiteColor];
    self.dblab = dblab;
    dblab.backgroundColor = KcolorHex(@"#FE5402");
    dblab.textAlignment = NSTextAlignmentCenter;
    [DTKTool YJ:kwt(9) andView:dblab];
    [dbBtn addSubview:dblab];
    [dblab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(kwt(11));
        make.centerX.equalTo(dbBtn).offset(kwt(25));
        make.width.height.offset(kwt(18));
    }];
    
    
    
    UIButton * ywcBtn = [UIButton buttonWithType:0];
    self.ywcBtn = ywcBtn;
    ywcBtn.addTarget(self,@selector(ywcBtnClick));
    ywcBtn.addNormalText(@"已完成").addNormalColor(KcolorHex(@"#222222")).addFont(kFont(17));
    [topview addSubview:ywcBtn];
    [ywcBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.top.offset(0);
        make.left.equalTo(dbBtn.mas_right);
        make.width.offset(kwt(80));
    }];
    
    
    UIView * btnline = [UIView new];
    self.btnline = btnline;
    btnline.backgroundColor = KcolorHex(@"#4965FE");
    btnline.frame = CGRectMake(kwt(27), kwt(47), kwt(26), kwt(3));
    [topview addSubview:btnline];
    
    
    UIView * line = [UIView new];
    line.backgroundColor = KcolorHex(@"#D8D8D8");
    [topview addSubview:line];
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.left.right.offset(0);
        make.height.offset(0.5);
    }];
    
    [self.view addSubview:self.tableview];
    self.tableview.backgroundColor = KcolorHex(@"#ECEDEE");
    [self.tableview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.offset(0);
        make.top.equalTo(topview.mas_bottom);
    }];
    MJWeakSelf
    [self addFooterView:^{
        [weakSelf addMoreData];
    }];
    [self addHeaderView:^{
        [weakSelf refreshingData];
    }];
    
    
//    [self btnClickWithbtn:self.qbBtn];
    if(self.state == 0){
        [self qbBtnClick];
    } else if(self.state == 1){
        [self dbBtnClick];
        btnline.frame = CGRectMake(kwt(27 + 80) , kwt(47), kwt(26), kwt(3));
    } else if(self.state == 2){
        [self ywcBtnClick];
        btnline.frame = CGRectMake(kwt(27 + 160) , kwt(47), kwt(26), kwt(3));
    }
}
- (void)btnClickWithbtn:(UIButton *)btn{
    
    self.qbBtn.addFont(kFont(17));
    self.dbBtn.addFont(kFont(17));
    self.ywcBtn.addFont(kFont(17));
    btn.addFont(kCFont(19));
    self.btnline.mj_x = btn.mj_x + kwt(27);

}
- (void)qbBtnClick{
    self.state = 0;
    [self btnClickWithbtn:self.qbBtn];
    [self refreshingData];

}
- (void)dbBtnClick{
    self.state = 1;
    [self btnClickWithbtn:self.dbBtn];
    [self refreshingData];

}
- (void)ywcBtnClick{
    self.state = 2;
    [self btnClickWithbtn:self.ywcBtn];
    [self refreshingData];

}
-(void)refreshingData{
    self.pageNo = 1;
    [self.modelArray removeAllObjects];
    [self loadNewData];
}

///先获取时间数据
- (void)loadTimeApi{
    if(self.task){
        [self.task cancel];
        [self.view hideBusyHUD];
        return;
    }
    [self.view showBusyHUD];
    NSMutableDictionary * dict = [NSMutableDictionary dictionary];
    [dict setObject:self.executeStartTime forKey:@"executeStartTime"];
    [dict setObject:self.executeEndTime forKey:@"executeEndTime"];
    [dict setObject:self.user forKey:@"user"];

    self.task = [SCNetManger PostTaskStatusWithDict:dict andCompetionHandlerBlock:^(HTTPDicBase * model) {
        [self.view hideBusyHUD];
        self.task = nil;
        if(model.code == 200){
            myQuestTimeListModel * Model = [myQuestTimeListModel yy_modelWithDictionary:model.result];
            self.model = Model;
            if(self.model.number > 0){
                self.dblab.hidden = NO;
                self.dblab.text = [NSString stringWithFormat:@"%ld",(long)self.model.number];
            } else {
                self.dblab.hidden = YES;
            }
            [self refreshingData];
        } else {
            if([model.message isEqualToString:@"结束时间不可大于当前时间,请检查!"]){//特殊处理
                [self refreshingData];
            } else {
                [self.view showWarning:model.message];
            }
        }
    }];
    
}
- (void)loadNewData {
    if(self.modeltask){
        [self.modeltask cancel];
        [self.view hideBusyHUD];
    }
    [self.view showBusyHUD];
    NSMutableDictionary * dict = [NSMutableDictionary dictionary];
    [dict setObject:@(self.pageNo) forKey:@"pageNo"];
    [dict setObject:@(self.pageSize) forKey:@"pageSize"];
    [dict setObject:self.executeTime forKey:@"executeTime"];
    [dict setObject:self.user forKey:@"user"];
    [dict setObject:self.pondName forKey:@"pondName"];
    [dict setObject:self.pondId forKey:@"pondId"];
    if(self.state){
        [dict setObject:@(self.state) forKey:@"state"];
    }
    
   self.modeltask = [SCNetManger PostTaskListWithDict:dict andCompetionHandlerBlock:^(HTTPDicBase * model) {
       [self.view hideBusyHUD];
       self.modeltask = nil;
       if(model.code == 200){
           NSArray * array = [NSArray yy_modelArrayWithClass:myQuestListModel.class json:model.result[@"records"]];
           if(self.userId.length < 1 || [self.userId isEqualToString:[UserInfoModel shared].userID]){
               for (myQuestListModel * usermodel in array) {
                   usermodel.isMy = YES;
               }
           }
           [self.modelArray addObjectsFromArray:array];
           if(array.count == 0 && self.modelArray.count > 0){
               [self.tableview.mj_footer endRefreshingWithNoMoreData];
           } else {
               [self.tableview.mj_footer endRefreshing];
           }
           [self.tableview.mj_header endRefreshing];
           [self.tableview reloadData];
       } else {
           [self.view showWarning:model.message];
       }
   }];
}
- (CGFloat)verticalOffsetForEmptyDataSet:(UIScrollView *)scrollView {
    return kwt(100);
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if(!self.headerview){
        myQuestHeaderView * headerview = [myQuestHeaderView NewView];
        self.headerview = headerview;
    }
    MJWeakSelf
    self.headerview.openTimeBlock = ^(NSString * _Nonnull day, NSString * _Nonnull startDay, NSString * _Nonnull endDay) {
        //        if(startDay.length > 0){
        weakSelf.executeStartTime = startDay;
        weakSelf.executeEndTime = endDay;
        weakSelf.executeTime = day;
        [weakSelf loadTimeApi];
        [weakSelf.modelArray removeAllObjects];
        [weakSelf.tableview reloadData];
//        }
    };
    ///执行人
    self.headerview.openZXRlock = ^{
        [weakSelf openZXR];
    };
    ///编组加池塘
    self.headerview.openTKBZBlock = ^{
        [weakSelf openTKBZ];
    };
    self.headerview.model = self.model;
    self.headerview.xspondName = self.xspondName;
    self.headerview.user = self.xsuser;
    return self.headerview;
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return kwt(190);
}

- (NSInteger)tableView:(nonnull UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return  self.modelArray.count;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if(self.modelArray.count > indexPath.row){
        return self.modelArray[indexPath.row].cellH;
    }
    return 0;
}

- (nonnull UITableViewCell *)tableView:(nonnull UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
    
    
    myQuestTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"myQuestTableViewCell"];
    if (cell == nil) {
        cell = [[myQuestTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"myQuestTableViewCell"];
    }
    if(self.modelArray.count > indexPath.row){
        cell.model = self.modelArray[indexPath.row];
    }
    MJWeakSelf
    cell.openDKBlock = ^(myQuestListModel * _Nonnull model) {
        ClockViewController * vc = [ClockViewController new];
        vc.ID = model.ID;
        vc.userId = weakSelf.userId;
        vc.userName = weakSelf.userName;
        [weakSelf.navigationController pushViewController:vc animated:YES];
    };
    cell.openZJBlock = ^(myQuestListModel * _Nonnull model) {
        TransferTaskViewController * vc = [TransferTaskViewController new];
        vc.ID = model.ID;
        vc.userId = weakSelf.userId;
        vc.userName = weakSelf.userName;
        [weakSelf.navigationController pushViewController:vc animated:YES];
    };
    cell.openQXBlock = ^(myQuestListModel * _Nonnull model) {
        CancelTaskViewController * vc = [CancelTaskViewController new];
        vc.ID = model.ID;
        [weakSelf.navigationController pushViewController:vc animated:YES];
    };
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    return cell ;
    
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
//    if(self.modelArray[indexPath.row].state == 1){
//        ///进新界面
//        ClockViewController * vc = [ClockViewController new];
//        vc.ID = self.modelArray[indexPath.row].ID;
//        vc.userId = self.userId;
//        vc.userName = self.userName;
//        [self.navigationController pushViewController:vc animated:YES];
//    }
    
}
- (void)openTKBZ{
    ///选编组和池塘
    [self.view showBusyHUD];
    [SCNetManger PostPondTissueGetPondTissueListWithDict: [NSMutableDictionary dictionary] andCompetionHandlerBlock:^(HTTPArrBase * model) {
        [self.view hideBusyHUD];
        if(model.code ==200){
            NSArray <getPondTissueListModel *>* array = [NSArray yy_modelArrayWithClass:getPondTissueListModel.class json:model.result ];
            NSLog(@"%@",array);
            MJWeakSelf
            [DTChoosePersonListShowView showViewWithArray:array andBlock:^(getPondTissueListModel * _Nonnull pondModel) {
                [weakSelf openTKWithtissueId:pondModel.ID andName:pondModel.TJname];
            } andCZBlock:^{
                
                    weakSelf.pondId = @"";
                    weakSelf.pondName =@"";
                    weakSelf.xspondName = @"";
                    [weakSelf refreshingData];
            }];
        } else {
            [self.view showWarning:model.message];
        }
    }];
}
- (void)openTKWithtissueId:(NSString *)tissueId andName:(NSString *)name{
    [self.view showBusyHUD];
    NSMutableDictionary * dict = [NSMutableDictionary dictionary];
    [dict setObject:tissueId forKey:@"tissueId"];
    [SCNetManger PostTaskPondListWithDict:dict  andCompetionHandlerBlock:^(HTTPArrBase * model) {
        [self.view hideBusyHUD];
        if(model.code ==200){
            NSArray <getPondTissueListModel *>* array = [NSArray yy_modelArrayWithClass:getPondTissueListModel.class json:model.result ];
            MJWeakSelf
            NSMutableArray * nameArray = [NSMutableArray array];
            for (getPondTissueListModel * tkmodel in array) {
                [nameArray addObject:tkmodel.name];
            }
            [YTSearchStringShowView showViewWithTitle:@"池塘名称" andDateArray:nameArray andBlock:^(NSString * _Nonnull str) {
                for (getPondTissueListModel * tkmodel in array) {
                    if([tkmodel.name isEqualToString:str]){
                        weakSelf.pondId = tkmodel.ID;
                        weakSelf.pondName = tkmodel.name;
                        weakSelf.xspondName = [NSString stringWithFormat:@"%@-%@",name,tkmodel.name];
                        [weakSelf refreshingData];
                        return;
                    }
                }
            }];
        } else {
            [self.view showWarning:model.message];
        }
    }];
}
- (void)openZXR{
    
    [self.view showBusyHUD];
    MJWeakSelf
    [SCNetManger PostGetPositionAndUserByOrgCodeWithDict: [NSMutableDictionary dictionary] andCompetionHandlerBlock:^(HTTPArrBase * model) {
        [self.view hideBusyHUD];
        if(model.code ==200){
            NSArray <PositionUserModel *>* modelarray = [NSArray yy_modelArrayWithClass:PositionUserModel.class json:model.result];
            
            for (PositionUserModel * pmodel in modelarray) {
                for (PondUserModel * usermodel in pmodel.userModelList) {
                    if ([self.user isEqualToString:usermodel.userId]) {
                        usermodel.isSeled = YES;
                    }
                }
            }
            
            [SearchPersonInCchargeShowView showviewWithTitle:@"执行人" andArray:modelarray andBlock:^(NSString * _Nonnull ID) {
                
                for (PositionUserModel * pmodel in modelarray) {
                    for (PondUserModel * usermodel in pmodel.userModelList) {
                        if ([ID isEqualToString:usermodel.userId]) {
                            self.user = usermodel.userId;
                            self.xsuser = usermodel.realName;
                            [weakSelf.tableview reloadData];
                            return;
                        }
                    }
                }
            }];
        } else {
            [self.view showWarning:model.message];
        }
    }];
    
    
}


@end
